﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace AutoRename
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            this.fdMain.SelectedPath = Application.StartupPath;
            this.textBox1.Text = this.fdMain.SelectedPath;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.labMsg.Text = "";
            if (fdMain.ShowDialog() == DialogResult.OK)
            {
                this.textBox1.Text = fdMain.SelectedPath;               
            }
        }

        static void RenameFile(string dir)
        {
            string[] files = Directory.GetFiles(dir);
            FileInfo _fi;
            foreach (string s in files)
            {
                _fi = new FileInfo(s);
                if (_fi.Name.Split('.').Length>2 && _fi.Name.IndexOf(AppDomain.CurrentDomain.FriendlyName)==-1) //文件名中含有.号才替换
                {
                    File.Move(s, String.Format("{0}\\{1}{2}", _fi.DirectoryName, _fi.Name.Substring(0, _fi.Name.LastIndexOf(".")).Replace(".", "~"), _fi.Extension));
                }
            }
            string[] dirs = Directory.GetDirectories(dir);
            foreach (string s in dirs)
            {
                RenameFile(s);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.labMsg.Text = "";
            string dir = this.textBox1.Text.Trim();
            if (dir == "" || !System.IO.Directory.Exists(dir)) return;
            try
            {
                RenameFile(dir);
                this.labMsg.Text = "操作成功";
            }
            catch (Exception ex)
            {
                this.labMsg.Text = ex.Message;
            }
        }
    }
}
